package meetn.battle.database.server;

import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.http.*;

import com.google.appengine.api.rdbms.AppEngineDriver;
import com.google.cloud.sql.jdbc.Connection;
import com.google.cloud.sql.jdbc.ResultSet;

public class DatabaseServer extends HttpServlet {
	 java.sql.Connection c = null;

	 
	 public void doGet(HttpServletRequest req, HttpServletResponse resp)
	            throws IOException {
		 try {
		DriverManager.registerDriver(new AppEngineDriver());
		c = DriverManager.getConnection("127.0.0.1/android");
		 String key = req.getParameter("key");
		 if (key.equals("1"))
		 {
			 String punkte = req.getParameter("punkte");
		     String spieler = req.getParameter("spieler");
			 String host = req.getParameter("host");
		     String fraktion = req.getParameter("fraktion");
			 String ort = req.getParameter("ort");
		     String zeit = req.getParameter("zeit");
			 String datum = req.getParameter("datum");
			 String statement ="INSERT INTO warmachine VALUES(?,?,?,?,?,?,?) ";
			  PreparedStatement stmtinsert = c.prepareStatement(statement);
			  stmtinsert.setString(1, punkte);
			  stmtinsert.setString(2, spieler);
			  stmtinsert.setString(3, host);
			  stmtinsert.setString(4, fraktion);
			  stmtinsert.setString(5, ort);
			  stmtinsert.setString(6, zeit);
			  stmtinsert.setString(7, datum);
			      int success = 2;
			      success = stmtinsert.executeUpdate();
			      if(success == 1) {
			        System.out.println("<html><head></head><body>Success! Redirecting in 3 seconds...</body></html>");
			      } else if (success == 0) {
			        System.out.println("<html><head></head><body>Failure! Please try again! Redirecting in 3 seconds...</body></html>");
			      }
			}
		 Statement stmtselect = c.createStatement(); 
		 java.sql.ResultSet rs;
		 rs = stmtselect.executeQuery("Select Name from warmachine");
		 while(rs.next()){
			 String lastName = rs.getString("Name");
			 System.out.print(lastName);
		 }
		 c.close();
		 
	 }catch (SQLException e) {
	        e.printStackTrace();
	      }finally {
	          if (c != null) 
	              try {
	                c.close();
	              } catch (SQLException ignore) {
	                }
	        } resp.setHeader("Refresh","3; url=/guestbook.jsp");
		 
	 }

}
